<template>
  <el-dialog
    :title="title"
    :visible.sync="addDialog"
    @close="close"
  >
    <el-form ref="roleForm" :model="roleForm" :rules="rules" label-width="100px" class="demo-ruleForm">
      <el-form-item label="角色名称" prop="name">
        <el-input v-model="roleForm.name" />
      </el-form-item>
      <el-form-item label="权限选择">
        <el-tree
          ref="tree"
          :data="treeData"
          show-checkbox
          default-expand-all
          node-key="id"
          check-strictly
          check-on-click-node
          highlight-current
          :default-checked-keys="roleForm.menuIds"
          :props="defaultProps"
        />
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button plain @click="resetForm('roleForm')">重 置</el-button>
      <el-button @click="closeAddDialog">取 消</el-button>
      <el-button type="primary" @click="submitForm('roleForm')">确 定</el-button>
    </span>
  </el-dialog>
</template>
<script>
export default {
  props: {
    roleForm: {
      type: Object,
      default: () => {
        return {
          name: '',
          menuIds: [],
          id: ''
        }
      }
    },
    treeData: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      // 直接将props中数据赋值给data在整个生命周期中只生效一次
      // defaultCheckedKeys: this.roleForm.menuIds,
      addDialog: false,
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      rules: {
        name: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    title: function() {
      // 监听父组件传递的 id
      if (this.roleForm.id === '') {
        return '添加角色'
      } else {
        return '修改角色'
      }
    },
    // 获取直接 roleForm.menuIds 都行
    defaultCheckedKeys: function() {
      return this.roleForm.menuIds
    }
  },
  methods: {
    close() {
      this.clearForm()
    },
    closeAddDialog() {
      this.addDialog = false
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
      this.$refs.tree.setCheckedKeys([])
      this.clearForm()
    },
    clearForm() {
      this.roleForm.id = ''
      this.roleForm.name = ''
      this.roleForm.menuIds = []
      this.$refs.tree.setCheckedKeys([])
      this.$refs['roleForm'].resetFields()
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.roleForm.menuIds = []
          const checkedKeys = this.$refs.tree.getCheckedKeys()
          checkedKeys.forEach(e => {
            this.roleForm.menuIds.push(e)
          })
         
          this.$emit('addRole', this.roleForm)
        } else {
          return false
        }
      })
    }
  }
}
</script>
